package pkg.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.sourceforge.stripes.action.After;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import pkg.dao.EntityDAO;
import pkg.entity.Teacher;
import pkg.entity.User;
import pkg.filter.TeacherFilter;
import pkg.filter.UserFilter;

public class RegisterActionBean extends BaseActionBean {

    private User user;
    private String repeatEmail;
    private String repeatPassword;
    private List<Teacher> teachers;

    public RegisterActionBean() {
    }

    @DefaultHandler
    public Resolution view() {
        return new ForwardResolution("/Register.jsp");
    }

    public Resolution register() throws IOException {
        EntityDAO sb = new EntityDAO();

        if (user == null) {
            addError("Please enter the missing information");
            return getContext().getSourcePageResolution();
        }

        if (user.getEmail() == null) {
            addError("user.email", "Email is required.");
        } else {
            if (!user.getEmail().equals(repeatEmail)) {
                addError("repeatEmail", "Emails do not match.");
            }
        }
        if (user.getPassword() == null) {
            addError("user.password", "Password is required.");
        } else {
            if (user.getPassword().length() < 5)
            {
                addError("user.password", "Password must be at least 5 characters/digits long.");
            }
            if (!user.getPassword().equals(repeatPassword)) {
                addError("repeatPassword", "Passwords do not match.");
            }
        }
        if (user.getFirstName() == null) {
            addError("user.firstName", "First Name is required.");
        }
        if (user.getLastName() == null) {
            addError("user.lastName", "Last Name is required.");
        }
        if (user.getPhoneNumber() == null) {
            addError("user.phoneNumber", "Phone Number is required.");
        }
        List<String> children = new ArrayList<String>();
        List<Long> teachers = new ArrayList<Long>();

        children.add(user.getChildName1());
        children.add(user.getChildName2());
        children.add(user.getChildName3());
        children.add(user.getChildName4());

        teachers.add(user.getChildTeacherId1());
        teachers.add(user.getChildTeacherId2());
        teachers.add(user.getChildTeacherId3());
        teachers.add(user.getChildTeacherId4());

        boolean kidsClean = true;
        int missing = 0;

        for(int i = 0; i < 4; i++) {
            if (children.get(i) != null && (teachers.get(0) == null || teachers.get(0) == -1)) {
                addError("user.childName" + (i + 1), "Please select a teacher for " + children.get(i));
                kidsClean = false;
            }
            if (children.get(i) == null || children.get(i).trim().length() == 0) {
                children.set(i, null);
                teachers.set(i, -1L);
            }
            if (children.get(i) == null) {
                missing = missing + 1;
            }
            if (teachers.get(i) != null && teachers.get(i) == -1) {
                teachers.set(i, null);
            }
        }

        if (missing == 4) {
            addError("user.childName1", "Please enter at least one of your children.");
        }

        if (kidsClean) {
            // Compact the children list
            Iterator<String> sit = children.iterator();
            while(sit.hasNext()) {
                if (sit.next() == null) {
                    sit.remove();
                }
            }

            Iterator<Long> lit = teachers.iterator();
            while(lit.hasNext()) {
                if (lit.next() == null) {
                    lit.remove();
                }
            }
            // Re-expand the list to 4
            while(children.size() < 4) {
                children.add(null);
                teachers.add(null);
            }
        }

        if (!getContext().getValidationErrors().isEmpty()) {
            return getContext().getSourcePageResolution();
        }
        user.setEmail(user.getEmail().toLowerCase());

        EntityDAO dao = new EntityDAO();
        UserFilter f = new UserFilter();
        f.setEmail(user.getEmail());

        User u = (User)dao.findOneByFilter(f);

        if (u != null) {
            addError("user.email", user.getEmail() + " is already in use, please choose another email.");
            return getContext().getSourcePageResolution();
        }

        user.setId(null);
        user.setEmail(user.getEmail().toLowerCase());
        user.setChildName1(children.get(0));
        user.setChildName2(children.get(1));
        user.setChildName3(children.get(2));
        user.setChildName4(children.get(3));
        user.setChildTeacherId1(teachers.get(0));
        user.setChildTeacherId2(teachers.get(1));
        user.setChildTeacherId3(teachers.get(2));
        user.setChildTeacherId4(teachers.get(3));
        user.setAdmin(false);

        user = dao.update(user);
        getSession().setAttribute("user", user);
        return new ForwardResolution("/FinishRegistration.jsp");
    }

    @After(stages=LifecycleStage.BindingAndValidation)
    public void loadRequestIfErrors() {
        loadLookups();
    }

    public void loadLookups() {
        teachers = new ArrayList<Teacher>();
        Teacher empty = new Teacher();
        empty.setId(-1L);
        empty.setLastName("None");
        teachers.add(empty);
        EntityDAO dao = new EntityDAO();
        TeacherFilter f = new TeacherFilter();
        teachers.addAll(dao.findAllByFilter(f));
    }

    //<editor-fold defaultstate="collapsed" desc=" Setters/Getters ">
    public User getUser() {
        return user;
    }

    public void setUser(User category) {
        this.user = category;
    }

    public String getRepeatEmail() {
        return repeatEmail;
    }

    public void setRepeatEmail(String repeatEmail) {
        this.repeatEmail = repeatEmail;
    }

    public String getRepeatPassword() {
        return repeatPassword;
    }

    public void setRepeatPassword(String repeatPassword) {
        this.repeatPassword = repeatPassword;
    }

    public List<Teacher> getTeachers() {
        return teachers;
    }

    public void setTeachers(List<Teacher> teachers) {
        this.teachers = teachers;
    }

    //</editor-fold>

}
